package com.xc.h05.service.weichen.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xc.h05.entity.Question;
import com.xc.h05.entity.Reply;
import com.xc.h05.entity.User;
import com.xc.h05.mapper.QuestionMapper;
import com.xc.h05.mapper.ReplyMapper;
import com.xc.h05.mapper.UserMapper;
import com.xc.h05.service.weichen.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public int add(Reply reply) {
        reply.setCreateTime(new Date());
        int add = replyMapper.add(reply);
        return add;
    }

    @Override
    public int delete(int id) {
        int delete = replyMapper.delete(id);
        return delete;
    }

    @Override
    public int update(Reply reply) {
        int update = replyMapper.update(reply);
        return update;
    }

    @Override
    public PageInfo<Reply> findByPage(int pageNum, int pageSize, Reply reply) {
        PageHelper.startPage(pageNum,pageSize);
        List<Reply> list = replyMapper.findByPage(reply);
        for (Reply rp : list) {
            Question question = questionMapper.findById(rp.getQuestionId());
            rp.setQuestion(question);
            User user = userMapper.findById(rp.getUserId());
            rp.setUser(user);
        }

        PageInfo<Reply> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<Reply> findAll() {
        List<Reply> list = replyMapper.findAll();
        return list;
    }

    // 根据qid查询该问题下所有回复的信息
    @Override
    public List<Reply> findByQid(int qid) {
        List<Reply> list = replyMapper.findByQid(qid);
        for (Reply rp : list) {
            User user = userMapper.findById(rp.getUserId());
            rp.setUser(user);
            if (rp.getFId() != 0) {
//                User fUser = userMapper.findById(rp.getFId());
//                rp.setFUser(fUser);
                // 得到被回复的回复对象
                Reply byRId = replyMapper.findByRId(rp.getFId());
                // 得到被回复的回复对象的用户
                User user1 = userMapper.findById(byRId.getUserId());
                rp.setFUser(user1);
            }
        }
        return list;
    }
}
